package com.luo.gmall.scheduled.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luo.gmall.scheduled.entity.Cart;
import com.luo.gmall.scheduled.mapper.CartMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * XxlJob开发示例（Bean模式）
 * 开发步骤：
 * 1、在Spring Bean实例中，开发Job方法，方式格式要求为 "public ReturnT<String> execute(String param)"
 * 2、为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobLogger.log()" 打印执行日志；
 */
@Component
@Slf4j
public class CartAsyncAdd {


    private static final String ADD_CART_EXCEPTION = "cart:exception";

    private static final String CART_PREFIX = "cart:info:";

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @XxlJob("cartAsyncAdd")
    public ReturnT<String> execute(String param) {

        BoundSetOperations<String, String> boundSetOps = redisTemplate.boundSetOps(ADD_CART_EXCEPTION);

        // 1.pop弹出数据，直接弹出需要重新添加购物车到mysql中的userId，
        String userId = boundSetOps.pop();

        while (!StringUtils.isBlank(userId)) {
            // 根据userId先删除数据库对应的所有数据
            cartMapper.delete(new QueryWrapper<Cart>().eq("user_id", userId));
            // 然后根据userId获取redis中对应的购物车信息，将购物车信息添加到数据库
            BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(CART_PREFIX + userId);
            List<Object> cartJsons = boundHashOps.values();
            if (!CollectionUtils.isEmpty(cartJsons)) {
                cartJsons.forEach(cartJson -> {
                    Cart cart = JSON.parseObject(cartJson.toString(), Cart.class);
                    cartMapper.insert(cart);
                });
            }
            userId = boundSetOps.pop();
        }
        return ReturnT.SUCCESS;
    }
}